package com.yz.kronos.schedule.handle;

import com.google.common.base.Joiner;
import com.yz.kronos.schedule.client.KubernetesClient;
import com.yz.kronos.schedule.model.RequestDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author shanchong
 * @date 2021/2/6
 **/
@EnableAsync
@Service
public class ScheduleHandler {

    @Autowired
    private KubernetesClient kubernetesClient;
    private final static Joiner JOINER = Joiner.on("-");
    private final Set<String> runningIdSet = new HashSet<>();

    /**
     * 批量调用任务
     * @param requestDtoList 任务集合
     */
    @Async
    public void handle(final List<RequestDto> requestDtoList) {
        String flowId = String.valueOf(System.currentTimeMillis());
        runningIdSet.add(flowId);
        Synchronizer synchronizer = Synchronizer.build(flowId, requestDtoList);
        for (int i = 0; i < requestDtoList.size(); i++) {
            if (!runningIdSet.contains(flowId)) {
                break;
            }
            RequestDto requestDto = requestDtoList.get(i);
            int shareTotal = requestDto.getShareTotal();
            String image = requestDto.getImage();
            String resources = requestDto.getResources();
            String cmd = requestDto.getCmd();
            String executor = requestDto.getExecutor();
            String namespace = requestDto.getNamespace();
            kubernetesClient.handle(namespace, JOINER.join(flowId, i), shareTotal, resources, image, cmd, executor);
            synchronizer.await(i);
        }
    }

    public boolean interrupt(final String id) {
        Synchronizer.clear(id);
        return runningIdSet.remove(id);
    }

}
